package co.fitstart.market.handler.impl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import co.fitstart.market.handler.ImageConvertHandler;
import sun.misc.BASE64Encoder;

@SuppressWarnings("restriction")
@Repository("imageConvertHandler")
public class ImageConvertHandlerImpl implements ImageConvertHandler{
    
    private HttpURLConnection httpUrl = null;  
    
    private static final Logger logger = LoggerFactory.getLogger(ImageConvertHandlerImpl.class);
    
    /** 
     * 从URL中读取图片,转换成流形式. 
     * @param destUrl 
     * @return 
     */  
    private InputStream saveToFile(String destUrl){  
          logger.trace("ImageConvertHandler - saveToFile - imageUrl is [{}]", destUrl);
        URL url = null;  
        InputStream in = null;   
        try{  
            url = new URL(destUrl);  
            httpUrl = (HttpURLConnection) url.openConnection();  
            httpUrl.connect();  
            httpUrl.getInputStream();  
            in = httpUrl.getInputStream();            
            return in;  
        }catch (Exception e) {  
            e.printStackTrace();  
        }  
        return null;  
    }  
      
    /** 
     * 读取输入流,转换为Base64字符串 
     * @param input 
     * @return 
     */  
    private String GetImageStrByInPut(InputStream input) {  
        
        ByteArrayOutputStream outStream = null;
        // 读取图片字节数组  
        try {  
            outStream = new ByteArrayOutputStream();  
            //创建一个Buffer字符串  
            byte[] buffer = new byte[1024];  
            //每次读取的字符串长度，如果为-1，代表全部读取完毕  
            int len = 0;  
            //使用一个输入流从buffer里把数据读取出来  
            while( (len=input.read(buffer)) != -1 ){  
                //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度  
                outStream.write(buffer, 0, len);  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        
     // 对字节数组Base64编码  
        return new BASE64Encoder().encode(outStream.toByteArray());
    }  
      
    /*
     * (non-Javadoc)
     * @see co.fitstart.market.handler.ImageConvertHandler#convert(java.lang.String)
     */
    public String convert(String imageUrl) {
        
        // 获取图片转换成inputStream
        InputStream inputStream = this.saveToFile(imageUrl);
        
        // 读取输入流，转换成Base64字符串
        String imageBase64 = this.GetImageStrByInPut(inputStream);
        return imageBase64;
    }

}
